import {defineStore} from "pinia";
import type {UserInfo} from "@/api/types";
import userApi from "@/api/user";
import {usePermissionStore} from "@/store/permission";

type UserState = {
    currentUser: UserInfo | null;
}

export const useUserStore = defineStore(
    'user',
    {
        state: (): UserState  => {
            return {
                currentUser: null,
            };
        },
        persist: {
            storage: sessionStorage, // localStorage 或 sessionStorage
            key: 'userInfo', // 自定义Storage存储的名称
        },
        actions: {
            async fetchCurrentUser() {
                this.currentUser = await userApi.me();
                // https://juejin.cn/post/7086723723385896996
                //const permissionsData: Array<string> = this.currentUser?.permissions ? this.currentUser.permissions : [];
                const permissionsData: Array<string> = this.currentUser?.permissions ? this.currentUser.permissions : new Array<string>();
                /*console.log("permissionsData");
                console.log(permissionsData);*/
                await usePermissionStore().generateRoutes(permissionsData);
            },
            async clearInfo(): Promise<void> {
                this.currentUser.$reset();
            }
        },
    }
);